package edu.hawaii.halealohacli.kmj;

import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
//import org.wattdepot.resource.sensordata.jaxb.SensorData;
import org.wattdepot.resource.source.jaxb.Source;
import org.wattdepot.util.tstamp.Tstamp;
/**
 * Retrieves total energy used at a given location on a given date.
 * 
 * @author jesse elfalan, adapted by Kamana Akina
 */
public class DailyEnergy implements Command {

  double energyConsumed = 0;
  double formatEnergy = 0;
  int interval = 0;
  XMLGregorianCalendar startStamp = null;
  XMLGregorianCalendar stopStamp = null;
  String name;
  String input;
  
  /**
   * Constructor for Daily-Energy.
   * 
   * @param client WattDepotClient
   * @param tower Name of the tower
   * @param inputTime date
   */
  public DailyEnergy(WattDepotClient client,String tower, String inputTime) {
    
    //initialize local variables
    name = tower;
    input = inputTime;

    try {
      startStamp = Tstamp.makeTimestamp(input + "T00:00:00.000-10:00");
    }
    catch (Exception e) {
      System.err.println("Unable to create start timestamp");
    }
    try {
      stopStamp = Tstamp.incrementDays(startStamp, 1);
    }
    catch (Exception e) {
      System.err.println("Unable to create stop timestamp");
    }
    
    //get Energy of desired source
   try {
       Source source = client.getSource(name);
       energyConsumed = client.getEnergyConsumed(source.getName(),
       startStamp, stopStamp,interval);  
       formatEnergy = Math.round(energyConsumed / 1000);
   } 
   catch (NotAuthorizedException e) {
     System.err.println("Not authorized to view source");
   }
   catch (ResourceNotFoundException e) {
     System.err.println("Source name not found");
   }
   catch (BadXmlException e) {
     System.err.println("server provided bad xml:" + e.toString());
   }
   catch (MiscClientException e) {
     System.err.println("problem encountered with server:" + e.toString());
   }
   if (energyConsumed == 0) {
     System.err.println("Unable to retrieve energy consumption data");
   }
   
}

 @Override
 public void printResult() {
    System.out.println( "Total energy consumption by " +
    name + " on " + input + " was " + formatEnergy + " kWh");
    
  }
}